<template>
  <div>
    <el-badge :value="waringunreadcount" class="item" :max="99" :offset="[-2, 0]" :show-zero="false"
      style="margin-right: 24px;    margin-top: -2px;">
      <img src="@/assets/message/waring.png" style="width: 22px; cursor: pointer; height: 22px"
        @click="gowaringMessage()" alt="" />
    </el-badge>
    <el-badge :value="unreadcount" class="item" :max="99" :offset="[-2, 0]" :show-zero="false"
      style="margin-right: 24px">
      <img src="@/assets/message/message.png" style="width: 24px; cursor: pointer; height: 24px" @click="goMessage()"
        alt="" />
    </el-badge>
  </div>

</template>

<script setup>
import { ElNotification } from 'element-plus'
import { http } from '@/utils/http'
import config from '@/config'
import WS from '@/utils/ws.js'

const router = useRouter()
const unreadcount = ref(0)
const waringunreadcount = ref(0)
let uncountIntervalId
const userStore = useUserStore()
const ismounted = ref(false)
const audio = new Audio()
const ws = new WS({
  url: `ws://${userStore.wsenv}/info/message/`,
  onMessage(data) {
    if (data.level != undefined) {
      if (data.level !== 4) {
        if (data.level == 3) {
          audio.src = 'http://tools.app.qubit-dance.com/sound/msg.mp3'
          audio.play()
        } else {
          audio.src = 'http://tools.app.qubit-dance.com/sound/defeat.mp3'
          audio.play()
        }
      } else {
        audio.src = 'http://tools.app.qubit-dance.com/sound/success.mp3'
        audio.play()
      }
      ElNotification({
        title: '消息通知',
        icon: '',
        customClass: 'message_class',
        dangerouslyUseHTMLString: true,
        message: data.message,
        onClick() {
          goMessage()
        },
      })
    }
  },
})

const levels = { 1: '普通', 2: '重要', 3: '警告', 4: '成功' }
const colors = { 1: '#3711d8;', 2: '#ff5f58', 3: '#feac2e', 4: '#1cc535' }

const goMessage = () => {
  router.replace('message')
}

const gowaringMessage = () => {
  router.replace('messagewaring')
}

const getunreadcount = () => {
  clearInterval(uncountIntervalId)
  if (ismounted.value) {
    http.get('/message/unread_count').then(res => {
      unreadcount.value = res.data.unread_count
      waringunreadcount.value = res.data.level_gte_5
      uncountIntervalId = setInterval(() => {
        getunreadcount()
      }, 10000)
    })
  }

}

onMounted(() => {
  ismounted.value = true
  getunreadcount()
})
onUnmounted(() => {
  ismounted.value = false
  clearInterval(uncountIntervalId)
  ws.close()

})
</script>

<style lang="scss" scoped></style>

<style>
.message_class {
  width: 384px;
  padding: 20px 24px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.2);
  background-color: #fff;
  border-radius: 0;
}

.message_class .el-notification__icon {
  display: none;
}

.message_class .el-notification__group {
  margin: 0;
}

.message_class .el-notification__content {
  margin-top: 16px;
}
</style>